#include <iostream>
#include <fstream>
#include <ctime>

using namespace std;

#define BUF_SIZE		1024

void ifStreamTest(const string&);
void ofStreamTest(const string&);

void fileIOStreamTest()
{
	string fileName("TIky.tiky");
	
	ofStreamTest(fileName);
	ifStreamTest(fileName);
}

void ifStreamTest(const string &fileName)
{
	ifstream inFile;
	inFile.open(fileName.c_str(), ios_base::binary);
	
	if(!inFile)
	{
		cout << "File is locked by another process." << endl;
		return;
	}
	
	size_t size = 1024;
	char* line = new char[size + 1];
	memset(line, '\0', size);
	while(!inFile.eof())
	{
		inFile.getline(line, size);
		cout << (strlen(line) > 0 ? line : "") << endl;
	}

	inFile.clear(); // clear any existing errors
	inFile.close();
}

void ofStreamTest(const string &fileName)
{
	ofstream outFile;
	outFile.open(fileName.c_str(), ios_base::app | ios_base::binary | ios_base::out);
	if(!outFile){
		cout << "File is not ready now" << endl;
		return;
	}

	time_t rawTime;
	struct tm* timeInfo;
	time(&rawTime);
	timeInfo = localtime(&rawTime);
	char *ch = asctime(timeInfo);
	outFile.write(ch, strlen(ch));
	outFile.write("\n", strlen("\n"));

	size_t bufSize = BUF_SIZE;
	string line;
	char *cline = new char[bufSize];
	memset(cline, '\0', bufSize + 1);

	while(cin >> cline)
	{
		if(0 == strcmp(cline, "-q") || 0 == strcmp(cline, "-Q"))
			break;
		outFile.write(cline, strlen(cline));
		outFile.write("\n", strlen("\n"));
	}
	outFile.flush();
	outFile.clear();
	outFile.close();
}